package com.colorlight.cloud.grandshow.entity.instructions;

import com.colorlight.cloud.grandshow.api.GrandShowEntityScheduleActions;
import com.colorlight.iot.proto.grandshow.instruction.GrandShowInstruction;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import com.colorlight.cloud.grandshow.entity.po.*;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Demon
 * @description 加密指令
 * @date 22/3/2024  上午8:59
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Slf4j
public class Encrypt implements GrandShowEntityScheduleActions {
	private InputMsg input;
	private OutputMsg output;
	
	@Override
	public ByteString objectConvertBytes() {
		final GrandShowInstruction.Encrypt.InputMsg.Builder inputMsg =
				GrandShowInstruction.Encrypt.InputMsg.newBuilder();
		final GrandShowInstruction.Encrypt.Builder builder =
				GrandShowInstruction.Encrypt.newBuilder();
		inputMsg.setDetail(this.getInput().getAuthorizationDetail().toProto());
		builder.setInput(inputMsg);
		return builder.build().toByteString();
	}
	
	@Override
	public Encrypt byteConvertObject(ByteString bytes) {
		GrandShowInstruction.Encrypt encrypt = null;
		try {
			encrypt = GrandShowInstruction.Encrypt.parseFrom(bytes);
		} catch (InvalidProtocolBufferException e) {
			log.error("", e);
		}
		Objects.requireNonNull(encrypt);
		
		//上报消息为空
		GrandShowInstruction.Encrypt.OutputMsg output = encrypt.getOutput();
		
		Encrypt.OutputMsg outputMsg = new Encrypt.OutputMsg();
		outputMsg.setDeviceAuthResultInfo(new DeviceAuthResultInfo().formProto(output.getDeviceAuthResultInfo()));
		List<SenderAuthResultInfo> collect = output.getSenderAuthResultInfoList().stream().map(e -> new SenderAuthResultInfo().formProto(e)).collect(Collectors.toList());
		outputMsg.setSenderAuthResultInfo(collect);
		this.setOutput(outputMsg);
		return this;
	}
	
	@Data
	@NoArgsConstructor
	@Builder
	@AllArgsConstructor
	public static class InputMsg implements Serializable {
		private AuthorizationDetail authorizationDetail;
	}
	
	@Data
	@NoArgsConstructor
	@AllArgsConstructor
	@Builder
	public static class OutputMsg implements Serializable {
		private DeviceAuthResultInfo deviceAuthResultInfo;
		private List<SenderAuthResultInfo> senderAuthResultInfo;
	}
	
}
